package com.vma.order.service;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.vma.order.vo.Offer;
import com.vma.order.vo.OrderCommitVo;
import com.vma.order.vo.Spec;
import com.vma.shoes.bizModel.model.*;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by chenzui on 2017/4/13.
 */
public class OrderService {

    public static String commit(final OrderCommitVo order){
        final OrderCommitVo tmpOrder = order;
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmm");
        Random random = new Random();
        Date date = new Date();
        String dateStr =  df.format(date).toString();
        final String nbr= dateStr+random.nextInt(100);
        Db.tx(new IAtom() {
            public boolean run() throws SQLException {
                OrderList orderList = new OrderList().setOrderNbr(nbr).setCreateTime(new Date()).setStatus("1")
                        .setTotalCash(tmpOrder.getPrice()).setUserId(tmpOrder.getUserId()).setDiscount(0F);
                orderList.setAddressId(tmpOrder.getAddressId());
                orderList.setRemark(tmpOrder.getRemark());
                orderList.setDiscountDesc(order.getDiscountDesc());
                //查询邮费信息
                Address address = Address.dao.findById(tmpOrder.getAddressId());
                //查询邮费信息
                String province = address.getLocation().split("省")[0];
                Record postage = Db.findFirst("select * from postage_settings where location like ?","%"+province+"%");
                if(postage == null) postage = Db.findById("postage_settings",8);
                float topLine = postage.getFloat("top_line");
                float price = postage.getFloat("price");
                String status = postage.getStr("status");
                orderList.setFreight(price);
                //如果订单金额大于包邮设置，并且包邮生效
                if(orderList.getTotalCash() > topLine && "1".equals(status)){
                    orderList.setDiscount(price);
                }else {
                    orderList.setDiscount(0f);
                }

                orderList.save();
                for (Offer offer:tmpOrder.getOffers()) {
                    OrderOffer offerOffer = new OrderOffer();
                    offerOffer.setOrderId(orderList.getId()).setOfferId(offer.getId()).setOfferPrice(offer.getPrice()).setOfferVersion(1).setOfferPrice(offer.getPrice()).save();
                    Integer offerCnt = 0;
                    for (Spec spec:offer.getSpecs()) {
                        OrderItem item = new OrderItem();
                        item.setOrderOfferId(offerOffer.getId()).setItemNumber(spec.getNumber()).setColorId(spec.getColor()).setLengthId(spec.getLength()).save();
                        offerCnt+= spec.getNumber();
                    }
                    offerOffer.setOfferCnt(offerCnt).setStatus("1").update();
                    CartOffer.dao.findFirst("SELECT * FROM cart_offer WHERE user_id = ? AND offer_id = ? AND status = 1",tmpOrder.getUserId(),offer.getId())
                    .setStatus("0").update();
                }

                return true;
            }
        });
        Integer orderId = OrderList.dao.findFirst("SELECT * FROM orderList WHERE orderNbr = ?",nbr).getId();
        OrderAction orderAction = new OrderAction();
        orderAction.setCreateTime(new Date()).setOperation("创建订单").setOrderId(orderId).save();

        return orderId.toString();
        // TODO: 2017/4/13 返回商品信息、运费信息、优惠信息、订单编号

    }

    public static Map confirmInit(String nbr){
        Map result = new HashMap();
        OrderList order = OrderList.dao.findFirst("select * from orderList where orderNbr = ?",nbr);
        Integer userId = order.getUserId();
        //查询地址
        List<Address> address = Address.dao.find("SELECT * FROM address WHERE user_id = ? AND status = 1",userId);
        result.put("address",address);
        //查询运费信息
        List<Record> postage = Db.find("select * from postage_settings where location like SELECT * FROM postage_settings");
        result.put("postage",postage);
        //查询商品图片
        List<OrderOffer> offers = OrderOffer.dao.find("SELECT * FROM order_offer WHERE order_id = ? LIMIT 3",order.getId());
        List<String> imgs = new ArrayList<String>();
        for (OrderOffer offer:offers) {
            int offerId = offer.getOfferId();
            OfferImg img = OfferImg.dao.findFirst("SELECT * FROM offer_img WHERE offer_spec_id = ?",offerId);
            imgs.add(img.getUrl());
        }
        result.put("imgs",imgs);

        result.put("order",order);
        return result;
    }


    /**
     * 订单确认，确认地址、折扣方案
     * @param orderId
     * @param addressId
     * @param userId
     */
    public static Map confirm(Integer orderId,Integer addressId,Integer userId,String remark){
        Map result = new HashMap();
        result.put("code","0");
        result.put("msg","success");
        Address address = Address.dao.findById(addressId);
        //校验地址是否该客户
        if(address.getUserId() != userId){
            result.put("code","-1");
            result.put("msg","地址信息错误");
        }else {
            OrderList orderList = OrderList.dao.findById(orderId);
            orderList.setAddressId(addressId).setRemark(remark);

            //查询邮费信息
            String province = address.getLocation().split("省")[0];
            Record postage = Db.findFirst("select * from postage_settings where location like SELECT * FROM postage_settings WHERE location like '%?%'",province);
            int topLine = postage.getInt("top_line");
            float price = postage.getFloat("price");
            String status = postage.getStr("status");

            //如果订单金额大于包邮设置，并且包邮生效
            if(orderList.getTotalCash() > topLine && "1".equals(status)){
                orderList.setDiscount(price);
            }else {
                orderList.setDiscount(0f);
            }
            orderList.update();

        }
        return result;

    }

    public static Page<OrderList> qryOrderList(String orderNbr,String status,Integer cPage,Integer pSize,String start,String end,Integer userId){
        String condition = "";
        List<String> param = new ArrayList<String>();
        if(start != null && !"".equals(start)){
            condition += "and ol.create_time > ? ";
            param.add(start);
        }
        if(end != null && !"".equals(end)){
            condition += "and ol.create_time < ? ";
            param.add(end);
        }
        if(status != null && !"".equals(status)){
            condition += "and ol.status = ? ";
            param.add(status);
        }
//        if(phone != null && !"".equals(phone)){
//            condition += "and market_name like ? ";
//            param.add("%"+marketName+"%");
//        }
        if(orderNbr != null && !"".equals(orderNbr)){
            condition += "and ol.orderNbr like ? ";
            param.add("%"+orderNbr+"%");
        }
        if(userId != 0 ){
            condition += "and user_id = ? and ol.status not in ('0') ";
            param.add(String.valueOf(userId));
        }
        Page<OrderList> orders = OrderList.dao.paginate(cPage,pSize,"SELECT ol.*,u.phone ",
                "FROM orderList ol,user u where ol.user_id = u.id "+condition+" order by ol.id desc"
                ,param.toArray());

        //添加商品图片等信息
        List<OrderList> list = orders.getList();
        for (OrderList orderList:list) {
            Integer offerCnt = 0;
            List<OrderOffer> offers = OrderOffer.dao.find("SELECT * FROM order_offer WHERE order_id = ?",orderList.getId());
            List<OfferImg> imgs = new ArrayList<OfferImg>();
            for (OrderOffer offer:offers) {
                OfferImg img = OfferImg.dao.findFirst("SELECT * FROM offer_img WHERE offer_spec_id =?",offer.getOfferId());
                imgs.add(img);
                offerCnt += offer.getOfferCnt();
            }
            orderList.put("imgs",imgs);
            orderList.put("offerCnt",offerCnt);
            orderList.put("statusDesc",getStatus(Integer.valueOf(orderList.getStatus())));
        }


        return orders;
    }


    public static Map qryOrderDetail(String id){
        Map result = new HashMap();

        //获取订单的基本信息
        OrderList orderList = OrderList.dao.findById(id);
        result.put("id",orderList.getId());
        result.put("orderNbr",orderList.getOrderNbr());
        result.put("wuliuNbr",orderList.getLogistics());
        result.put("wuliuType",orderList.getWuliuType());
        result.put("createTime",orderList.getCreateTime());
        result.put("status",getStatus(Integer.valueOf(orderList.getStatus())));
        result.put("statusInt",orderList.getStatus());
        result.put("discount",orderList.getDiscount());
        result.put("freight",orderList.getFreight());
        result.put("phone",Db.findFirst("select * from user where id = ?",orderList.getUserId()).get("phone"));
        result.put("orderFee",orderList.getTotalCash());
        if(orderList.getAddressId() == null){
            result.put("address","");
        }else {
            Address address = Address.dao.findById(orderList.getAddressId());
            result.put("address", address.getLocation()+address.getDetail());
            result.put("addressObj", address);

        }
        //商品数量
        int offersCnt = 0;

        //商品信息
        List<OrderOffer> offers = OrderOffer.dao.find("select * from order_offer where order_id = ?",orderList.getId());
        for(OrderOffer offer:offers){
            int offerCnt = 0;
            List<OrderItem> items = OrderItem.dao.find("SELECT * FROM order_item WHERE order_offer_id = ?",offer.getId());
            List<Spec> specs = new ArrayList<Spec>();
            for (OrderItem item:items) {
                Spec spec = new Spec();
                spec.setId(item.getId());
                spec.setColor(item.getColorId());
                spec.setLength(item.getLengthId());
                spec.setColorDesc(SpecItem.dao.findById(item.getColorId()).getSpecValue());
                spec.setLengthDesc(SpecItem.dao.findById(item.getLengthId()).getSpecValue());
                spec.setNumber(item.getItemNumber());
                specs.add(spec);
                offersCnt += item.getItemNumber();
                offerCnt += item.getItemNumber();
            }
            offer.put("desc",offerDesc(specs));
            offer.put("specs",specs);
            offer.put("number",offerCnt);
            offer.put("offerName", com.vma.shoes.bizModel.model.Offer.dao.findById(offer.getOfferId()).getOfferName());
//            offer.put("offerName")
        }
        result.put("offerCnt",offersCnt);
        result.put("offers",offers);

        //操作记录
        List<OrderAction> actions = OrderAction.dao.find("select * from order_action where order_id = ?",orderList.getId());
        result.put("actions",actions);

        return result;
    }
    static String offerDesc(List<Spec> specs){
        String desc ="";
        for (Spec spec:specs) {
            desc += spec.getColorDesc()+"、"+spec.getLengthDesc()+"、"+spec.getNumber()+"  ";
        }
        return desc;
    }

    static String getStatus(Integer status){
        String res = "";
        switch (status){
            case 1: res = "待付款";break;
            case 2: res = "待发货";break;
            case 3: res = "待收货";break;
            case 4: res = "完成";break;
            case 0: res = "取消";break;
        }
        return res;
    }

    public static Record qryOrderCount(Integer userId){
        Map result = new HashMap();
        Record record = Db.findFirst("SELECT\n" +
                "  (\n" +
                "    SELECT COUNT(1)\n" +
                "    FROM orderList o\n" +
                "    WHERE o.status = 1 AND o.user_id = ?) waitingForPay,\n" +
                "  (SELECT count(1)\n" +
                "   FROM orderList o\n" +
                "   WHERE o.status = 2 AND o.user_id = ?) waitingForSend,\n" +
                "  (SELECT count(1)\n" +
                "   FROM orderList o\n" +
                "   WHERE o.status = 3 AND o.user_id = ?) waitingForCheck,\n" +
                "  (SELECT count(1)\n" +
                "   FROM orderList o WHERE o.user_id = ? and o.status not in ('0')) allCnt\n" +
                "FROM dual",userId,userId,userId,userId);
        return record;
    }


    public static Map initDataForOrderCommit(Integer userId){
        Map result = new HashMap();
        Address address = Address.dao.findFirst("SELECT id,phone,location,detail,reciver_name FROM address WHERE `default`=1 AND status = 1 AND user_id = ?",userId);
        List<PostageSettings> postageSettingses = PostageSettings.dao.find("SELECT * FROM postage_settings");
        for(PostageSettings p:postageSettingses){
            if(address.getLocation().contains(p.getLocation())){
                result.put("postageSettingses",p);
            }
        }
        if(!result.containsKey("postageSettingses")){
            for(PostageSettings p:postageSettingses){
                if(p.getLocation().equals("其他")){
                    result.put("postageSettingses",p);
                }
            }
        }
        result.put("address",address);
        return result;
    }


    public static List<OrderOffer> qryOfferListByOrderId(Integer orderId){
        List<OrderOffer> offers = OrderOffer.dao.find("SELECT oo.id,oo.offer_id,o.offer_name,oo.offer_price FROM order_offer oo,offer o WHERE oo.offer_id = o.id " +
                "AND oo.order_id = ?",orderId);
        //商品数量
        for (OrderOffer offer:offers) {
            int offerId = offer.getOfferId();
            OfferImg img = OfferImg.dao.findFirst("SELECT * FROM offer_img WHERE offer_spec_id = ?",offerId);
            offer.put("imgUrl",img.getUrl());
            List<OrderItem> items = OrderItem.dao.find("SELECT\n" +
                    "  oi.item_number,\n" +
                    "  (SELECT spec_value\n" +
                    "   FROM spec_item si\n" +
                    "   WHERE si.id = oi.color_id)  color,\n" +
                    "  (SELECT spec_value\n" +
                    "   FROM spec_item si\n" +
                    "   WHERE si.id = oi.length_id) length\n" +
                    "FROM order_item oi\n" +
                    "WHERE oi.order_offer_id = ?",offer.getId());
            offer.put("choose",items);




        }
        return offers;
    }


    public static void updateStatus(Integer orderId,String status){
        OrderList orderList = OrderList.dao.findById(orderId);
        orderList.setStatus(status).update();

        if(status.equals("0")){
            OrderAction orderAction = new OrderAction();
            orderAction.setCreateTime(new Date()).setOperation("用户取消订单").setOpreationPeople("前台用户").setOrderId(orderList.getId()).save();
        }else if(status.equals("4")){
            OrderAction orderAction = new OrderAction();
            orderAction.setCreateTime(new Date()).setOperation("用户确认收货").setOpreationPeople("前台用户").setOrderId(orderList.getId()).save();
        }
    }
}
